package news.newstopic.dao;

import news.newstopic.entity.NewsTopic;
import news.util.BaseDao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AddTopicDaoImpl implements IAddTopicDao{
    //mysql baseDao
    //oracle baseDao
    private BaseDao baseDao = new BaseDao();
    @Override
    public void addTopic(String topicName) {
        try {
            baseDao.openDB();
            String sql = "INSERT INTO news_topic(topicname) values(?)";
            baseDao.ps = baseDao.conn.prepareStatement(sql);
            baseDao.ps.setString(1,topicName);
            baseDao.ps.execute();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * @Author GongXL
     * @Description  查询所有的主题
     * @Date 14:58 2022/3/3
     * @Param []
     * @return java.util.List<news.newstopic.entity.NewsTopic>
     **/
    @Override
    public List<NewsTopic> getNewsTopicList() {
        List<NewsTopic> newsTopicList = new ArrayList<>();
        baseDao.openDB();
        //sql, 每行加空格
        String sql = "select * from  news_topic";
        //预编译SQL，减少sql执行
        PreparedStatement ptmt = null;
        ResultSet rs = null;
        try {
            ptmt = baseDao.conn.prepareStatement(sql);
            //执行
            rs = ptmt.executeQuery();
            NewsTopic newsTopic = null;
            while(rs.next()){
                newsTopic = new NewsTopic();
                newsTopic.setId(rs.getInt("id"));
                newsTopic.setTopicName(rs.getString("topicname"));
                newsTopic.setCreatetime(rs.getDate("createtime"));
                newsTopicList.add(newsTopic);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return newsTopicList;
    }
}
